<?php

namespace App\Http\Controllers\utils;

use AlibabaCloud\Client\AlibabaCloud;
use Illuminate\Http\Request;
use App\Http\Controllers\admin\model\SmsModel;
use Illuminate\Support\Facades\DB;

class ToolUtil
{



    /**
     * 删除oss文件
     * @param $object oss存储地址（一维数组或者字符串）
     * @return mixed
     * @throws \OSS\Core\OssException
     */
    public static function deleteOssFile($object){

        if(empty($object)){
            return FALSE;
        }

        $oss = new OssClient(env('OSS_ACCESS_KEY_ID'),env('OSS_ACCESS_KEY_SECRET'),env('OSS_URL'));

        if(is_array($object)){
            foreach ($object as $key => $value) {
                $str[] = explode('/',$value);
            }

            $new_str = [];
            foreach ($str as $key => $value) {
                $name = '';
                foreach ($value as $k => $v) {
                    if($k > 2){
                        $name .= $v.'/';
                    }
                }
                $new_str[] = rtrim($name,'/');
            }

            try {

                $oss->deleteObjects(env('OSS_BUCKET'),$new_str);
                return TRUE;

            }catch (\Exception $exception){
                return $exception->getMessage();
            }

        }else{
            $str = explode('/',$object);
            $name = '';
            foreach ($str as $k => $v) {
                if($k > 2){
                    $name .= $v.'/';
                }
            }
            $new_str = rtrim($name,'/');

            try {         

                if($oss->doesObjectExist(env('OSS_BUCKET'),$new_str)){
                    $oss->deleteObject(env('OSS_BUCKET'),$new_str);
                    return TRUE;
                }else{
                    // throw new \Exception("oss没有这个文件");
                    return FALSE;
                }

            }catch (\Exception $exception){
                return $exception->getMessage();
            }

        }

    }

    /**
    * CURL下载文件 成功返回文件名，失败返回false
    * @param $url
    * @param $suffix
    * @param string $savePath
    * @return bool|string
    */
    public static function downFile($url,$suffix = '',$savePath = './upload'){

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, TRUE);  //需要response header
        curl_setopt($ch, CURLOPT_NOBODY, FALSE);  //需要response body
        $response = curl_exec($ch);
        //分离header与body
        $header = '';
        $body = '';
        if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == '200') {
            $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); //头信息size
            $header = substr($response, 0, $headerSize);
            $body = substr($response, $headerSize);
        }
        curl_close($ch);
        
        $fileName = 'f'.time().mt_rand(1000,9999);

        $file = date('Ymd') . '/' . $fileName.$suffix;
        $fullName = rtrim($savePath, '/') . '/' . $file;
        //创建目录并设置权限
        $basePath = dirname($fullName);
        if (!file_exists($basePath)) {
            @mkdir($basePath, 0777, true);
            @chmod($basePath, 0777);
        }
        if (file_put_contents($fullName, $body)) {
            return $file;
        }

        return false;
    }

    
    /**
     * json返回方法
     * @param null $code 状态
     * @param null $msg 提示信息
     * @param array $data 数据
     * @param string $total 总数据量
     * @return false|string 返回信息
     */
    public static function returnJson($code=null,$msg=null,$data=[],$total=''){
        if($data){
            if($total){
                $str = ['code'=>$code?$code:200,'msg'=>$msg?$msg:'成功','data'=>$data,'total'=>$total];
            }else{
                $str = ['code'=>$code?$code:200,'msg'=>$msg?$msg:'成功','data'=>$data,];
            }
        }else{
            $str = ['code'=>$code?$code:200,'msg'=>$msg?$msg:'成功'];
        }
        return json_encode($str);
    }

    /**
     * 日志文件数据处理
     * @param $param
     * @return array
     */
    public static function checkLogArr($param){
        return [
            'ip'=>self::get_real_ip(),
            'remark'=>$param['remark'],
            'create_time'=>time()
        ];
    }

    /**
     * 处理批次
     * @param $data
     * @return array
     */
    public static function handleBatch($data,$param){
        $result = [];
        foreach ($data as $key=>$value){
            if($value[$param]){
                $batchArr = explode(',',$value[$param]);
                $batch = [];
                $batchStr = '';
                foreach ($batchArr as $k=>$val){
                    $batch[$k] = DB::table('t_batch')->where('id',$val)->value('name');
                }
                if($batch){
                    $batchStr = implode(',',$batch);
                }
                $value[$param] = $batchStr;
            }
            $result[$key]=$value;
        }
        return $result;
    }


    /**
     * 是否有权限
     * @param 
     * @return bool
     */
    public static function isPower($login_uid,$data_uid){
        $data_uid = (int)$data_uid;
        if(!self::isSuperAdmin($login_uid) && $data_uid != $login_uid){
            return false;
        }else{
            return true;
        }
    }


    /**
     * 是否超级管理员
     * @param $uid
     * @return bool
     */
    public static function isSuperAdmin($uid){
        $uid = (int)$uid;
        $auth_group_id = DB::table('t_admin')->where(['id'=>$uid])->value('group_id');
        if(!empty($auth_group_id) && $auth_group_id === 1){
            return true;
        }else{
            return false;
        }
    }


    /**
     * 是否管理员
     * @param $uid
     * @return bool
     */
    public static function isAdmin($uid){
        $uid = (int)$uid;
        $auth_group_id = DB::table('t_admin')->where(['id'=>$uid])->value('group_id');
        if(!empty($auth_group_id) && ($auth_group_id === 1 || $auth_group_id === 2)){
            return true;
        }else{
            return false;
        }
    }


    /**
     * 检查是否是管理员
     * @param 
     * @return array
     */
    public static function checkIsAdmin($group_id){

        $admin = [1,2];

        if(in_array($group_id,$admin)){
            $res = true;
        }else{
            $res = false;
        }

        return $res;
    }


    /**
     * 获取附件类型数组
     * @param 
     * @return array
     */
    public static function getFileTypeArray(){

        $type = [
            1=>'小程序二维码',
            2=>'操作指引图片',

        ];

        return $type;
    }

    /**
     * 获取附件类型
     * @param 
     * @return array
     */
    public static function getFileType(){

        $res = self::getFileTypeArray();

        $type = [];
        $num = 0;
        foreach ($res as $key => $value) {
            $type[$num]['type'] = $key;
            $type[$num]['type_name'] = $value;
            $num++;
        }

        return $type;
    }

    /**
     * 获取附件类型名称
     * @param 
     * @return string
     */
    public static function getFileTypeName($type){

        $res = self::getFileTypeArray();

        if(isset($res[$type])){
            $name = $res[$type];
        }else{
            $name = '';
        }
        
        return $name;
    }


    /**
     * 获取真实ip
     * @param 
     * @return false|string
     */
    public static function get_real_ip(){

        $ip=FALSE;

        //客户端IP 或 NONE

        if(!empty($_SERVER["HTTP_CLIENT_IP"])){

            $ip = $_SERVER["HTTP_CLIENT_IP"];

        }

        //多重代理服务器下的客户端真实IP地址（可能伪造）,如果没有使用代理，此字段为空

        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {

            $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);

            if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }

            for ($i = 0; $i < count($ips); $i++) {

                if (!eregi ("^(10│172.16│192.168).", $ips[$i])) {

                    $ip = $ips[$i];

                    break;

                }

            }

        }

        //客户端IP 或 (最后一个)代理服务器 IP
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);

    }


    /**
     * 获取阿里云短信验证码
     * @param $param
     * @return false|string
     * @throws \AlibabaCloud\Client\Exception\ClientException
     * @throws \AlibabaCloud\Client\Exception\ServerException
     */
    public static function aliSms($phone,$tem_code,$type = 0){

        $phone = self::filterStr($phone);
        $tem_code = self::filterStr($tem_code);

        if(empty($phone) || empty($tem_code)){
            return ['code'=>300,'msg'=>'参数不能为空'];
        }

        $code = rand(100000,999999);
        $query = [
            'RegionId'=>'cn-hangzhou',//使用的地区
            'PhoneNumbers'=>$phone,//手机号
            'SignName' => env('MODEL_CODE'),//签名
            'TemplateCode' => $tem_code,//模版code
            'TemplateParam' => "{'code':$code}",//参数  json格式
        ];

        $sms = SmsModel::queryFirst(['phone'=>$phone,'type'=>$type],['id','create_time']);

        if(!empty($sms) && ((int)$sms['create_time']) > (time()-30)){
            return ['code'=>303,'msg'=>'发送间隔不能少于30秒'];
        }

        AlibabaCloud::accessKeyClient(env('ALI_ACCESS_KEY_ID'),env('ALI_ACCESS_KEY_SECRET'))->regionId('cn-hangzhou')->asDefaultClient();

        $result = AlibabaCloud::rpc()
            ->product('Dysmsapi')
            ->version('2017-05-25')
            ->action('SendSms')
            ->method('POST')
            ->host('dysmsapi.aliyuncs.com')
            ->options([
                'query' => $query,
            ])->request();

        $sms_res = json_decode($result);
        if($sms_res->Code == 'OK'){

            if($sms){
                $res = SmsModel::edit(['id'=>$sms['id']],['code'=>$code,'create_time'=>time(),'is_use'=>0]);
            }else{
                $res = SmsModel::add(['phone'=>$phone,'code'=>$code,'create_time'=>time(),'type'=>$type,'is_use'=>0]);
            }

            if($res){
                return ['code'=>200,'msg'=>'短信验证码已发送成功'];
            }else{
                return ['code'=>301,'msg'=>'记录短信验证码失败'];
            }

        }
        return ['code'=>302,'msg'=>'发送短信验证码失败'];
    }


    /**
     * 过滤字符串
     * @param $str 字符串
     * @return string
     */
    public static function filterStr($str){
        $str = htmlspecialchars(trim($str),ENT_QUOTES);
        return $str;
    }


    /**
     * 验证器方法
     * @param $data 验证器返回数据
     * @return false|string
     */
    public static function checkValidate($data){
        if($data){
            foreach ($data as $value){
                return self::returnJson(401,$value);
            }
        }
        return null;
    }

    /**
     * 生成字符串
     * @param int $let 字符串长度
     * @return string
     */
    public static function randStr($let=6){
        $nameStr = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
        $randStr = '';
        for ($i=0;$i<$let;$i++){
            $randStr .=$nameStr[mt_rand(0,35)];
        }
        return $randStr;
    }

    /**
     * 计算分页
     * @param $param 参数
     * @param $count 总数量
     * @return mixed
     */
    public static function calculationPage($param,$count){
        if($param['pageSize']>=$count){
            $param['pageSize'] = $count;
        }
        if($param['pageSize']<=0){
            $param['pageSize'] = 0;
        }
        if($param['startSize']<=0){
            $param['startSize'] = 1;
        }
        $param['startSize'] = ($param['startSize']-1)*$param['pageSize'];
        return $param;
    }

    /**
     * 验证excel文件后缀
     * @param $param
     * @return bool
     */
    public static function checkExcelSuffix($param){
        $fileSuffixArr = ['xlsx','xls'];
        $fileName = $param['file']->getClientOriginalName();
        $fileNameArr = explode(',',$fileName);
        if(!in_array($fileNameArr[count($fileNameArr)-1],$fileSuffixArr)){
            return true;
        }
        return false;
    }

    /**
     * 判断存入日志文件是正确还是错误
     * @param $data
     * @param int $type
     * @return false|string
     */
    public static function handleSuccessOrError($data,$type=1){
        if($type){
            $data['code'] = 'success';
        }else{
            $data['code'] = 'error';
        }
        return json_encode($data);
    }

    /**
     * 返回原生limit
     * @param $param
     * @param $count
     * @return string
     */
    public static function calculationPageTwo($param,$count){
        $page = self::calculationPage($param,$count);
        return " limit $page[startSize],$page[pageSize]";
    }

    /**
     * 获取微信token
     * @param $param
     * @return false|string
     */
    /*public static function getToken($param){
        $appId = env('WX_APPID');
        $secret = env('WX_SECRET');
        $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$secret";
        $headerArray =array("Content-type:application/json;","Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
        $url1="https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$output[access_token]";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
        $output1 = json_decode(curl_exec($ch));
        return self::returnJson(200,'',$output1);
    }*/

}